<template>
  <div class="case">
    <na-table
      :datas.sync="tableData"
      :searchObj.sync="search"
      @updateDatas="getDataLists"
      @newAdd="newAddClick"
    >
    </na-table>
    <!-- 选择发货单 -->
    <el-dialog
      v-dialogDrag
      title="选择发货单"
      :visible.sync="isPickingVisible"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
    >
      <div class="dialogDody marDialog flex flex_column">
        <!-- 搜索     -->
        <div class="btnCon flex flex_between" style="border-bottom: none">
          <!--      搜索框-->
          <div class="search">
            <el-input
              v-model="deliverySearch.likeWords"
              prefix-icon="el-icon-search"
              placeholder="输入关键字"
              size="small"
              @keyup.enter.native="getSelectDeliveryList"
            >
            </el-input>
          </div>
        </div>
        <!-- 表格区域       -->
        <div class="tableCon lastTdNoBorder not pt0" style="padding: 16px">
          <el-table
            v-loading="purLoading"
            :data="deliveryLists"
            max-height="460"
            :row-class-name="tableRowClassName"
            border
            style="width: 100%"
          >
            <el-table-column
              prop="deliveryBillNo"
              label="发货单号"
              min-width="150"
            />
            <el-table-column
              prop="deliveryTypeName"
              label="发货类型"
              min-width="100"
            />
            <el-table-column
              prop="createTime"
              label="创建时间"
              show-overflow-tooltip
              min-width="110"
            />
            <el-table-column
              prop="createPersonName"
              label="申请人员"
              min-width="100"
            />
            <el-table-column
              prop="detailsCount"
              label="发货明细"
              min-width="90"
            />
            <el-table-column
              prop="expressSumQuantity"
              label="总数量"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              prop="deliveryRemark"
              label="备注"
              min-width="150"
              show-overflow-tooltip
            >
              <template scope="{row}">
                {{ row.deliveryRemark || "--" }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="100px"
              fixed="right"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="medium"
                  style="color: #606266"
                  @click="confirmSelecd(scope.row)"
                >
                  选择
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isPickingVisible=false">取 消</el-button>
        <el-button
          type="primary"
          size="mini"
          :disabled="isSelect"
          :loading="isSelect"
          @click="confirmSelecd"
        >确定</el-button>
      </span> -->
    </el-dialog>

    <!--  新建/编辑成品出库   -->
    <el-dialog
      :title="ops == 'add' ? '成品出库 - 新建' : '成品出库 - 查看'"
      :visible.sync="isAddDialog"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <div class="subTip">
          <span class="mr15"
            ><span class="mr5">出库单号：</span
            >{{ deliveryForm.outStockBillNo || "系统自动生成" }}</span
          >
          <span class="mr15"
            ><span class="mr5">创建日期：</span
            >{{ ops == 'add' ? dayjs().format("YYYY-MM-DD") : deliveryForm.createTime }}</span
          >
          <span class="mr15"
            ><span class="mr5">创建人员：</span>{{deliveryForm.creatorName || name }}</span
          >
        </div>
        <div class="addWuliaoBox">
          <el-form
            ref="deliveryForm"
            :model="deliveryForm"
            :rules="rules"
            label-width="95px"
            label-position="left"
            class="dialogForm dialogInlineForm"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="出库类型">
                  <el-select
                        filterable
                    v-model="deliveryForm.outStockType"
                    placeholder="请选择"
                    size="mini"
                    disabled
                  >
                    <el-option label="成品出库" :value="1"> </el-option>
                  </el-select>
                  <!-- <el-input
                    v-model="deliveryForm.outStockTypeName"
                    placeholder="请输入出库类型"
                    size="mini"
                    disabled
                  /> -->
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="关联单据">
                  <el-input
                    v-model="deliveryForm.associationBillNo"
                    placeholder="关联单据"
                    size="mini"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请人员">
                  <el-input
                    v-model="deliveryForm.requestPerson"
                    placeholder="请输入内容"
                    size="mini"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="所属客户">
                  <el-input
                    v-model="deliveryForm.customerName"
                    placeholder="所属客户"
                    size="mini"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="出库备注"
                  class="inlineText mt5"
                  prop="outStockBillRemark"
                >
                  <el-input
                    v-model="deliveryForm.outStockBillRemark"
                    type="textarea"
                    :disabled="disabled"
                    :rows="3"
                    placeholder="请输入出库备注"
                    size="mini"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="tableBox lastTdNoBorder">
            <div class="tt flex flex_between">
              <span class="fw">出库明细</span>
            </div>
            <el-table
              :data="deliveryForm.outStockMxList"
              :row-key="
                (row) => {
                  row.rowKey;
                }
              "
              border
              style="width: 100%"
            >
              <el-table-column
                label="产品名称"
                prop="productName"
                show-overflow-tooltip
                min-width="110"
              />
              <el-table-column
                label="版面"
                prop="productLayout"
                show-overflow-tooltip
                min-width="110"
              />
              <el-table-column
                label="版本"
                prop="productVersion"
                show-overflow-tooltip
                min-width="110"
              />
              <el-table-column
                label="成品型号"
                prop="productSpecificationName"
                show-overflow-tooltip
                min-width="110"
              />

              <el-table-column
                label="纸箱规格"
                prop="packageGuiGeNo"
                show-overflow-tooltip
                min-width="180"
              >
                <template slot-scope="{ row }">
                  <el-select
                        filterable
                    value-key="packageGuiGeNo"
                    size="mini"
                    v-model="row.cartonName"
                    :disabled="disabled"
                    @change="handlepackageGuiGeChange(row, $event)"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in row.guiGeList"
                      :key="item.packageGuiGeNo"
                      :label="item.cartonName"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="包装描述"
                prop="packageDescription"
                min-width="190"
              >
                <template slot-scope="{ row }">
                  {{ row.packageDescription || "选择后显示" }}
                </template>
              </el-table-column>
              <el-table-column label="库位" prop="stockArea" min-width="180">
                <template slot-scope="{ row }">
                  <el-cascader
                    v-model="row.stockArea"
                    size="mini"
                    ref="cascaders"
                    :disabled="disabled"
                    clearable
                    @change="handleStockAreaChange(row, $event)"
                    :options="row.wareHouseAreaList"
                    :props="{
                      label: 'wareHouseAreaName',
                      value: 'wareHouseAreaCode',
                      children: 'areaSheltList',
                    }"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="每箱数量"
                prop="eachBoxQuantity"
                show-overflow-tooltip
                min-width="110"
              >
                <template slot-scope="{ row }">
                  {{ row.eachBoxQuantity || "选择后显示" }}
                </template>
              </el-table-column>
              <el-table-column
                label="申请数量"
                prop="requestQuantity"
                show-overflow-tooltip
                min-width="110"
              />
              <el-table-column
                label="申请箱数"
                prop="requestBoxCount"
                show-overflow-tooltip
                min-width="110"
              >
              </el-table-column>
              <el-table-column
                label="库存箱数"
                prop="stockBoxCount"
                show-overflow-tooltip
                min-width="110"
              >
                <template slot-scope="{ row }">
                  {{ row.stockBoxCount }}
                </template>
              </el-table-column>
              <el-table-column
                label="库存数量"
                prop="productStockQuantity"
                show-overflow-tooltip
                min-width="110"
              >
                <template slot-scope="{ row }">
                  {{ row.productStockQuantity }}
                </template>
              </el-table-column>
              <el-table-column
                label="出库箱数"
                prop="outStockBoxs"
                show-overflow-tooltip
                min-width="110"
              >
                <template slot-scope="{ row }">
                  <el-input
                    v-model="row.outStockBoxs"
                    :disabled="disabled"
                    placeholder="出库箱数"
                    size="mini"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="出库数量"
                prop="outStockQuantity"
                min-width="90"
              >
                <template slot-scope="{ row }">
                  <el-input
                    v-model="row.outStockQuantity"
                    :disabled="disabled"
                    placeholder="出库数量"
                    size="mini"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="申请公斤数"
                prop="kilogramQuantity"
                show-overflow-tooltip
                min-width="110"
              >
                <template slot-scope="{ row }">
                  {{ row.requestKilogramQuantity }}
                </template>
              </el-table-column>
              <el-table-column
                label="公斤数"
                prop="kilogramQuantity"
                show-overflow-tooltip
                min-width="110"
              >
                <template slot-scope="{ row }">
                  <el-input
                    v-model="row.kilogramQuantity"
                    :disabled="disabled"
                    placeholder="公斤数"
                    size="mini"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                show-overflow-tooltip
                min-width="150"
                prop="outStockRemark"
              >
                <template slot-scope="{ row }">
                  <el-input
                    v-model="row.outStockRemark"
                    :disabled="disabled"
                    placeholder="备注"
                    size="mini"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="100px"
                fixed="right"
                align="center"
                v-if="!disabled"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="handleCopyRow(scope.row, scope.$index)"
                    >复制</el-button
                  >
                  <el-button
                    type="text"
                    v-if="scope.row.isCopy"
                    @click="handleDeleteRow(scope.row, scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddDialog = false">取 消</el-button>
        <!--  同意      -->
        <el-button
          v-if="!disabled"
          :loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveAdd"
          >同意</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import MixA from "@/utils/mixin";
const mixa = new MixA();
import naTable from "@/components/naTable";
import { mapGetters } from "vuex";
import { arraySort } from "@/utils";
export default {
  name: "",
  components: {
    naTable,
  },
  mixins: [mixa],
  computed: {
    ...mapGetters(["name", "userInfo"]),
  },
  data() {
    return {
      isSeeDialog: false,
      radioSelect: null, // 发货单选中值
      addLoading: false,
      isAddDialog: false,
      purLoading: false,
      isSelect: false,
      ops: "",
      disabled: false,
      storageLocations: [], // 库位列表
      isPickingVisible: false, // 发货单弹框是否打开
      currentRow: {}, // 选中的发货单
      searchLoading: false,
      deliveryForm: {
        associationBillNo: "", //关联单据号（发货单号）
        outStockBillRemark: "", //出库单备注
        receivingWay: "", //快递方式（收货方式）
        outStockTypeName: "",
        requestPerson:"",
        expressWay: "", //送货方式
        expressBillNo: "", //快递单号
        expressTime: "", //送货日期，格式：yyyy-MM-dd HH:mm:ss
        expressCost: 0, //快递费用
        paymentWay: "", //付费方式
        costAssumeDepartment: "", //费用部门
        expressGoodsWeight: 0, //快递物品重量（公斤数）
        expressGoodsCount: 0, //快递物品件数
        outStockMxList: [
          {
            associationOrderNo: "", //关联订单号
            productNo: "", //成品代码
            productStockNo: "", //成品规格编码
            outStockBoxs: 0, //出库箱数
            outStockQuantity: 0, //出库数量
            warehouseAreaCode: "", //出库库区代码
            areaShelfCode: "", //出库库位代码
            outStockRemark: "", //出库备注
          },
        ],
      },
      sendingTypeList: [], // 送货方式列表
      receivingTypeList: [], // 收货方式列表
      logisticsPaidList: [], // 付费方式
      departmentList: [], // 费用部门
      search: {
        QueryDataBaseFiled: "",
        pageIndex: 1,
        pageSize: 30,
        likeWords: "",
      }, // 搜索条件
      deliverySearch: {
        likeWords: "",
      },
      deliveryLists: [], // 发货单列表
      dataLists: [], // 成品出库列表
      total: 0,
      tableHeight: null,
      tableHead: [], // 表头
      rules: {},

      tableData: {
        headId: "head", //表头列显隐组件所需ID-避免多个页面id重复问题
        tableId: "outStockID", //表格列表key,也就是一条数据的唯一标识
        senior: false, //高级搜索是否显示
        disableWord: "", //是否禁用显示的字段
        disableStatus: "", //判断未禁用的状态值
        // addTitle: '', //新建按钮名称-为''则不显示，为undefine则为新建
        addPermission: "", //新建按钮权限
        addIcon: "", //新建按钮icon
        voidWord: "", //需要查询作废的字段
        statusList: [], //状态筛选条件列表
        statusWord: "", //状态筛选的字段
        refresh: true, //刷新按钮
        //表格按钮
        operationBtn: [
          {
            title: "查看", //按钮名称
            methodsName: "seeInfo", //按钮绑定方法的字段
          },
        ],
        //表格内容
        tbody: [],
        //表格表头
        thead: [],
      },
    };
  },
  created() {
    // 成品出库表头
    this.getTableHead();
    // 库区库位
    this.getStorageLocations();
    // 获取送货方式数据列表
    this.getSendList();
    // 获取收货方式数据列表
    this.getReceivingList();
    // 获取费用部门数据列表
    this.getDepartmentList();
    // 获取付费方式数据列表
    this.getPayTypeList();
  },
  mounted() {},
  methods: {
    // 获取付费方式数据列表
    getPayTypeList() {
      const params = {
        DictionaryCode: "LogisticsPaidType",
      };
      this.$api.warehouse.GetDictionaryByCode(params).then((res) => {
        this.logisticsPaidList = res;
      });
    },
    // 获取费用部门数据列表
    getDepartmentList() {
      this.$api.warehouse.GetDepartmentTreeData({}).then((res) => {
        this.departmentList = res;
      });
    },

    // 获取收货方式数据列表
    getReceivingList() {
      const params = {
        DictionaryCode: "ReceivingType",
      };
      this.$api.warehouse.GetDictionaryByCode(params).then((res) => {
        this.receivingTypeList = res;
      });
    },

    //复制明细
    handleCopyRow(row, index) {
      let arr = JSON.parse(JSON.stringify(row));
      arr.rowKey = Date.now();
      this.deliveryForm.outStockMxList.splice(index, 0, arr);
      this.deliveryForm.outStockMxList[index+1].isCopy = true
    },

    //删除明细
    handleDeleteRow(row, index) {
      this.deliveryForm.outStockMxList.splice(index, 1);
    },


    // 获取送货方式数据列表 receivingTypeList
    getSendList() {
      const params = {
        DictionaryCode: "SendingType",
      };
      this.$api.warehouse.GetDictionaryByCode(params).then((res) => {
        this.sendingTypeList = res;
      });
    },
    // 查看
    seeInfo(row) {
      // this.isSeeDialog = true;
      this.ops = "see";
      this.disabled = true;
      const params = {
        queryBy: 1,
        queryValue: row.outStockBillNo,
      };
      this.$api.warehouse
        .GetOutStockDetailListByOutStockNo(params)
        .then((res) => {
          this.deliveryForm = res;
          this.deliveryForm.outStockMxList = this.deliveryForm.detailList
          this.deliveryForm.outStockMxList.forEach((k) => {
            k.guiGeList.forEach((j) => {
              if (k.packageGuiGeNo == j.packageGuiGeNo) {
                k.wareHouseAreaList = j.wareHouseAreaList;
                k.stockArea = [];
                k.stockArea[0] = k.areaShelfCode;
                k.stockArea[1] = k.warehouseAreaCode;
                k.cartonName = j.cartonName;
                k.packageDescription = j.productStockName;

                k.wareHouseAreaList.forEach((m) => {
                  if (k.areaShelfCode == m.wareHouseAreaCode) {
                    // row.areaShelfCode = m.wareHouseAreaCode;
                    m.areaSheltList.forEach((w) => {
                      debugger
                      if (k.warehouseAreaCode == w.wareHouseAreaCode) {
                        k.eachBoxQuantity = w.eachBoxQuantity;
                        k.productStockQuantity = w.productStockQuantity;
                        k.stockBoxCount = w.stockBoxCount;
                        // row.warehouseAreaCode = w.wareHouseAreaCode;
                        k.productStockNo = w.productStockNo;
                      }
                    });
                  }
                });
              }
            });
          });
          this.isAddDialog = true;
        });
    },
    //库位选择事件
    handleStockAreaChange(row, event) {
      row.wareHouseAreaList.forEach((k) => {
        if (event[0] == k.wareHouseAreaCode) {
          row.areaShelfCode = k.wareHouseAreaCode;
          k.areaSheltList.forEach((j) => {
            if (event[1] == j.wareHouseAreaCode) {
              row.eachBoxQuantity = j.eachBoxQuantity;
              this.$set(row,'productStockQuantity',j.productStockQuantity)
              // row.productStockQuantity = j.productStockQuantity;
              row.warehouseAreaCode = j.wareHouseAreaCode;
              row.stockBoxCount = j.stockBoxCount;
              row.productStockNo = j.productStockNo;
            }
          });
        }
      });
      console.log(row);
    },

    //纸箱规格选择事件
    handlepackageGuiGeChange(row, event) {
      row.packageDescription = event.productStockName;
      row.packageGuiGeNo = event.packageGuiGeNo;
      this.$set(row, "productStockQuantity", '');
      this.$set(row, "stockArea", []);
      this.$set(row, "wareHouseAreaList", event.wareHouseAreaList);
      // row.wareHouseAreaList = event.wareHouseAreaList
    },

    // 同意出库
    saveAdd() {
      let state = true
      this.deliveryForm.outStockMxList.forEach((item)=>{
        if(!item.areaShelfCode){
          state = false
        }
      })
      if(!state){
        this.$message.warning('请选择库位')
        return
      }
      const params = this.deliveryForm;
      this.$refs.deliveryForm.validate((valid) => {
        if (valid) {
          this.addLoading = true;
          this.$api.warehouse
            .CreateProductOutStockBill(params)
            .then(() => {
              this.addLoading = false;
              this.$message({
                message: "出库成功",
                type: "success",
              });
              this.isAddDialog = false;
              // 成品出库列表
              this.getDataLists();
            })
            .catch(() => {
              this.addLoading = false;
            });
        }
      });
    },
    // 成品发货单确认
    async confirmSelecd(row) {
      let obj = {
        queryBy: 0,
        queryValue: row.deliveryBillNo,
      };
      this.$api.warehouse.GetOutStockDetailListByDeliveryNo(obj).then((res) => {
        this.deliveryForm = res;
        this.deliveryForm.outStockMxList = this.deliveryForm.detailList
        this.disabled = false;
        this.isPickingVisible = false;
        this.isAddDialog = true;
      });
      this.deliveryForm.outStockTypeName = "成品出库";
      this.ops = "add";
      // this.deliveryForm.receivePerson = this.userInfo.employeeCode; // 申请人员代码
      this.deliveryForm.requestPerson = this.userInfo.employeeName; // 申请人员名称
      // this.isPickingVisible = false;
      // this.isAddDialog = true;
    },
    // 新建成品出库点击事件
    newAddClick() {
      this.isPickingVisible = true;
      // 发货单列表
      this.getSelectDeliveryList();
    },
    // 库区库位
    getStorageLocations() {
      const parmas = {
        warehouseCode: "",
      };
      this.$api.warehouse.GetStockQueryAreaTreeView(parmas).then((res) => {
        this.storageLocations = res;
      });
    },
    // 发货单列表
    getSelectDeliveryList() {
      this.purLoading = true;
      this.$api.warehouse
        .GetMatchProduceLogisticss(this.deliverySearch)
        .then((res) => {
          this.deliveryLists = res;
          this.purLoading = false;
        })
        .catch(() => {
          this.purLoading = false;
        });
    },
    // 给选中一行添加class
    tableRowClassName({ row }) {
      if (this.currentRow.id === row.id) {
        return "selectd";
      }
    },
    // 成品出库表头
    getTableHead() {
      const parmas = {
        tableCode: this.$config.outStockProductList,
      };
      this.$api.common.getAllTableHead(parmas).then((res) => {
        res.sort(arraySort("columnSort"));
        this.tableData.thead = res;
        // 成品出库列表
        this.getDataLists();
      });
    },
    // 成品出库列表
    getDataLists() {
      const params = this.search;
      this.searchLoading = true;
      this.$api.warehouse
        .GetPageProductOutStockBills(params)
        .then((res) => {
          this.tableData.tbody = res.list;
          this.search.total = res.totalCount;
          this.searchLoading = false;
        })
        .catch(() => {
          this.searchLoading = false;
        });
    },
    closeDialog() {},
  },
};
</script>
<style lang="scss" scoped>
.deliveryBox {
  height: calc(100% - 34px);
}

.spot {
  width: 6px;
  height: 6px;
  display: inline-block;
  border-radius: 100%;
}

.subTip {
  border-bottom: 1px #e6e6e6 solid;
  background: #f5f6f9;
  padding: 8px 16px;
}

.addWuliaoBox {
  padding: 10px 16px;

  .tableBox {
    margin-top: 16px;
    border: 1px solid #e6e6e6;
    border-bottom: none;
    border-radius: 8px 8px 0 0;
    overflow: hidden;

    .tt {
      height: 38px;
      line-height: 38px;
      padding-left: 16px;
      background: #f7f8fa;
      border-radius: 8px 8px 0 0;
    }
  }
}
</style>
